<template>
  <div class="product-list">
    <div class="search-list coll">
      <div class="main-btn">
        <div class="form-item">
          <span class="label">小说名称</span>
          <el-input size="default" v-model.trim="state.queryInfo.name" style="width: 130px; margin-right: 10px"
            clearable placeholder="请输入搜索的内容"></el-input>
        </div>
        <el-button type="primary" @click="getProductList" class="form-item"> 搜索 </el-button>

        <!-- <el-upload
          ref="importRef"
          accept=".xls,.xlsx "
          action="https://jsonplaceholder.typicode.com/posts/"
          :on-change="importExp"
          :show-file-list="false"
          :auto-upload="false"
          class="form-item"
        >
          <el-button type="primary"> 批量导入小说 </el-button>
        </el-upload> -->
        <el-upload ref="importRef" accept=".xls,.xlsx " action="https://jsonplaceholder.typicode.com/posts/"
          :on-change="importChapterAll" :show-file-list="false" :auto-upload="false" class="form-item">
          <el-button type="primary"> 一键导入剧集列表 </el-button>
        </el-upload>
        <el-button type="danger" @click="uploadChapterAll" class="form-item" :disabled="isLoading">
          一键映射剧集
        </el-button>

        <el-button type="danger" @click="removeCartoon(1)" style="margin-left: 10px"> 批量删除 </el-button>
        <el-button type="danger" @click="editVisible = true" style="margin-left: 10px"> 批量修改分类 </el-button>
        <!-- <el-button type="danger" @click="copyText('这是一个好看的')" style="margin-left: 10px"> 复制 </el-button> -->
        <!-- <el-upload
          accept=".xls,.xlsx "
          action="https://jsonplaceholder.typicode.com/posts/"
          :on-change="importImg"
          :show-file-list="false"
          :auto-upload="false"
          class="form-item"
        >
          <el-button type="primary"> 一键更换封面 </el-button>
        </el-upload> -->
      </div>
      <div class="carry-log">
        <p style="margin-bottom: 10px">执行日志</p>
        <div class="form-item">
          <el-input type="textarea" v-model="state.linkLog" rows="7" disabled resize="none"></el-input>
        </div>
      </div>
    </div>
    <div class="table-box coll">
      <el-table ref="workbenchTable" :height="state.tableHeight" :data="state.tableData" tooltip-effect="dark"
        empty-text="暂无数据" style="width: 100%" :header-cell-style="{
          textAlign: 'center',
          backgroundColor: '#f5f7fa'
        }" :cell-style="{ textAlign: 'center' }" :row-style="{ height: '80px' }"
        @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="60" fixed />
        <el-table-column label="序号" width="60">
          <template #default="scope">
            {{ scope.$index + 1 + (state.queryInfo.page - 1) * state.queryInfo.pageSize }}
          </template>
        </el-table-column>
        <el-table-column label="小说名称" min-width="120px" prop="name" />
        <el-table-column label="简介" show-overflow-tooltip min-width="160px" prop="intro" />
        <el-table-column label="封面" width="80px" align="center">
          <template #default="scope">
            <img v-if="scope.row.cover_lateral" :src="scope.row.cover_lateral" alt="" class="cover_img" />
            <img v-else src="~@/assets/images/default.jpg" alt="" class="cover_img" />
          </template>
        </el-table-column>
        <el-table-column label="阅读量" min-width="120px" prop="read" />
        <el-table-column label="点赞量" min-width="120px" prop="fabulous" />
        <el-table-column label="价格" min-width="120px" prop="price" />
        <el-table-column label="是否收费" min-width="120px" prop="is_vip">
          <template #default="scope">
            <span>{{ scope.row.charge == 0 ? '免费' : '收费' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" min-width="140px">
          <template #default="scope">
            <el-button size="small" type="danger" @click="editShow(scope.row.id)">编辑详情</el-button>
            <el-button size="small" type="danger" @click="removeCartoon(2, scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination">
        <el-pagination v-model:currentPage="state.queryInfo.page" v-model:page-size="state.queryInfo.pageSize"
          :page-sizes="[10, 20, 50, 100, 300]" background layout="sizes,prev, pager, next" :total="state.total"
          @size-change="handleSizeChange" @current-change="handleCurrentChange">
          <span style="margin-right: 5px">当前共{{ state.total }}条</span>
        </el-pagination>
      </div>
    </div>
    <el-dialog v-model="dialogEditVisible" width="68%" :destroy-on-close="true" :close-on-press-escape="false"
      :close-on-click-modal="false" @close="categoryClose">
      <CartoonEdit :sysId="state.sysId" :categoryList="state.categoryList" />
    </el-dialog>
    <el-dialog v-model="editVisible" title="批量修改分类" width="20%">
      <div class="add-content">
        <div class="form-item">
          <div class="label">分类名称：</div>
          <div class="cartoon-name">
            <el-select v-model="state.category_id" class="text-input">
              <el-option v-for="(item, index) in state.categoryList" :key="index" :label="item.name" :value="item.id">
              </el-option>
            </el-select>
          </div>
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="categoryClose">取消</el-button>
          <el-button type="primary" @click="editCategoryAll(state.category_id)">修改</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { reactive, getCurrentInstance, onMounted, watch, ref } from 'vue'
import { getTableHeight, ImportXlsx, copyText } from '@/hooks/utils'
import { dialogEditVisible, editVisible } from './ts/data'
import { cartoonDetail } from '@/network/model/cartoonModel'
import CartoonEdit from './components/cartoon-edit.vue'
import { ElMessage } from 'element-plus'

const isLoading = ref<Boolean>(false)

const state = reactive({
  tableData: [],
  queryInfo: {
    page: 1,
    pageSize: 10,
    name: ''
  },
  tableHeight: 0,
  total: 0,
  tableLoading: false,
  sysId: 0,
  categoryList: [],
  linkLog: '',
  category_id: ''
})
// const loadingInstance = ElLoading.service({
//   fullscreen:true,
//   text:'正在导入漫画信息'
// })
const multipleSelection = ref<cartoonDetail[]>([])

onMounted(() => {
  state.tableHeight = getTableHeight(400)
  getProductList()
  getCategory()
})
// 获取公共接口
// @ts-ignore
const { proxy } = getCurrentInstance()
const api = proxy.$api
const getProductList = async () => {
  const { code, data } = await api.getVideoList(state.queryInfo)
  if (code == 200) {
    state.tableData = data?.data
    state.total = data?.total
    console.log(data, 'data')
  }
}
async function getCategory() {
  const res = await api.getVideoCategory({ isAll: true })
  console.log(res, 'res');
  state.categoryList = res.data.data
  console.log(state.categoryList[0].id, 'state.categoryList[0].id')
}
function editShow(id: number) {
  state.sysId = id
  dialogEditVisible.value = true
}
// 批量删除
/**
 * @param type 1:批量删除 2:删除漫画
 */
async function removeCartoon(type: number, id: string = '') {
  let ids: any = []
  if (type == 1) {
    if (multipleSelection.value.length == 0) {
      return ElMessage.warning('请选择要删除的信息')
    }
    multipleSelection.value.forEach((item) => {
      ids.push(item.id)
    })
  } else {
    ids = id
  }
  console.log(ids, multipleSelection.value, 'multipleSelection.value')

  try {
    const res = await api.deleteVideo({ ids: ids.toString() })
    console.log(res, 'res')
    if (res.code == 200) {
      ElMessage.success(res.msg)
      await getProductList()
    } else {
      ElMessage.error(res.msg)
    }
  } catch (error) {
    console.log(error)
    ElMessage.error('删除失败')
  }
}
const handleSelectionChange = (val: cartoonDetail[]) => {
  multipleSelection.value = val
}
// 导入并上传漫画
async function importExp(file: File) {
  // state.linkLog = ''
  try {
    let res: any = await ImportXlsx(file)
    console.log(res, 'res')
    let head = {
      漫画名称: 'name',
      漫画简介: 'cartoon_introduction',
      作者: 'author',
      价格: 'price',
      是否vip: 'charge',
      封面: 'img_url',
      上家漫画ID: 'platform_comic',
      漫画详情封面: 'cover_lateral'
    }
    // loadingInstance
    const list = res.map((item: Object) => {
      const obj: any = {}
      for (const k in item) {
        if (head[k]) {
          obj[head[k]] = item[k]
        }
      }
      return obj
    })
    const chapterLength = list.length
    state.linkLog = ``
    state.linkLog = `开始导入小说`
    for (let i = 0; i < list.length; i++) {
      const item = list[i]
      let param = { ...item }
      param.category_id = state.categoryList[0].id
      // console.log(param,'param');
      const res = await api.addVideo(param)
      if (res.code == 200) {
        state.linkLog = `${i + 1}/${chapterLength}导入成功\n` + state.linkLog
      } else {
        state.linkLog = `${i + 1}/${chapterLength}导入失败,${res.msg}\n` + state.linkLog
      }
      console.log(res, '====>')
    }
  } catch (error) {
    state.linkLog = `导入失败\n` + state.linkLog
  }
  state.linkLog = `导入完成\n` + state.linkLog
  await getProductList()
  // state.linkLog = `导入完成\n` + state.linkLog
}
// 批量导入漫画章节
async function importChapterAll(file: File) {
  try {
    let res: any = await ImportXlsx(file)
    console.log(res, 'res')
    let head = {
      小说名称: 'title',
      章节别名: 'title_alias',
      上家章节ID: 'platform_chapter',
      上家漫画ID: 'platform_comic'
    }
    // loadingInstance
    const list = res.map((item: Object) => {
      const obj: any = {}
      for (const k in item) {
        if (head[k]) {
          obj[head[k]] = item[k]
        }
      }
      return obj
    })
    if (state.tableData.length == 0) {
      state.linkLog = `小说信息匹配失败，请检查是否存在小说信息\n` + state.linkLog
      return
    }
    for (let i = 0; i < state.tableData.length; i++) {
      const item: any = state.tableData[i]
      for (let index = 0; index < list.length; index++) {
        const v = list[index]
        console.log(v.platform_comic == item['platform_comic'], v.platform_comic, item['platform_comic'])

        if (v.platform_comic == item['platform_comic']) {
          console.log(v)
          let param = { ...v }
          param.comic_id = item.id
          delete param.url
          delete param.platform_comic

          const res = await api.addVideoChapter(param)
          if (res.code == 200) {
            state.linkLog = `章节列表${index + 1}/${list.length}导入成功\n` + state.linkLog
          } else {
            console.log(res, '====>')

            state.linkLog = `章节列表${index + 1}/${list.length}导入失败,${res.msg}\n` + state.linkLog
          }
        }
      }
      state.linkLog = `第${i + 1}小说章节导入完毕\n` + state.linkLog
    }
  } catch (error) {
    state.linkLog = `导入失败\n` + state.linkLog
  }
}
function categoryClose() {
  editVisible.value = false
  state.category_id = ''
}
// 批量修改分类
async function editCategoryAll(categoryId: string) {
  console.log(categoryId, 'categoryId', multipleSelection.value)
  const data = multipleSelection.value.length > 0 ? multipleSelection.value : state.tableData
  if (data.length == 0) {
    return ElMessage.warning('请选择要修改的数据')
  }
  state.linkLog = ``
  try {
    for (let i = 0; i < data.length; i++) {
      const item = data[i]
      item['category_id'] = Number(categoryId)
      const res = await api.editVideo(item)
      console.log(res, 'res')
      if (res.code == 200) {
        state.linkLog = `${item.name}${res.msg}\n` + state.linkLog
      } else {
        state.linkLog = `${item.name}${res.msg}\n` + state.linkLog
      }
    }
  } catch (error) {
    state.linkLog = `修改失败\n` + state.linkLog
  }
  editVisible.value = false
  state.category_id = ''
}
// 一键映射剧集
async function uploadChapterAll() {
  const data = multipleSelection.value.length > 0 ? multipleSelection.value : state.tableData
  if (data.length == 0) {
    return ElMessage.warning('请选择要修改的数据')
  }
  try {
    for (let i = 0; i < data.length; i++) {
      const item = data[i]
      const param = {
        comicId: item.platform_comic,
        type: 1
      }
      isLoading.value = true
      const res = await api.queryVideolDetail(param)
      if (res.code == 200) {
        state.linkLog = `开始上传剧集...`
        const chapterLength = res.data.length
        for (let index = 0; index < res.data.length; index++) {
          const item1 = res.data[index]
          item1.comic_id = item.id
          delete item1.platform_comic
          const res1 = await api.addVideoChapter(item1)
          if (res1.code == 200) {
            state.linkLog = `${index + 1}/${chapterLength}导入成功\n` + state.linkLog
          } else {
            state.linkLog = `${index + 1}/${chapterLength}导入失败,\n` + state.linkLog
          }
        }
      } else {
        ElMessage.error('IP限制，获取视频失败')
      }
    }
  } catch (error) {
    state.linkLog = `获取失败\n` + state.linkLog
  }
  state.linkLog = `上传完成...\n` + state.linkLog
  isLoading.value = false
}
async function importImg(file: File) {
  try {
    let res: any = await ImportXlsx(file)
    console.log(res, 'res')
    let head = {
      漫画详情封面: 'cover_lateral',
      上家漫画ID: 'comic_id'
    }
    const list = res.map((item: Object) => {
      const obj: any = {}
      for (const k in item) {
        if (head[k]) {
          obj[head[k]] = item[k]
        }
      }
      return obj
    })
    for (let i = 0; i < state.tableData.length; i++) {
      const item = state.tableData[i]
      for (let index = 0; index < list.length; index++) {
        const element = list[index]
        if (element.comic_id == item['platform_comic']) {
          const param = {
            id: item['id'],
            cover_lateral: element['cover_lateral']
          }
          await api.editVideo(param)
        }
      }
    }
  } catch (error) {
    console.log(error)
  }
}
const handleSizeChange = (val: number) => {
  // console.log(`${val} items per page`)
  state.queryInfo.pageSize = val
  getProductList()
}
const handleCurrentChange = (val: number) => {
  state.queryInfo.page = val
  getProductList()
  // console.log(`current page: ${val}`)
}
</script>

<style scoped lang="less" src="./css/productList.less">

</style>
